# -*- coding: utf-8 -*-
import os
import codecs
import json
from shutil import copyfile, move, copy
# from bs4 import BeautifulSoup
from chardet import detect


class reStr(str):
	_str = ''
	isdir = False

	def __setattr__(self, key, value):
		if key == 'isdir' & isinstance(value, bool):
			self.isdir = value
		else:
			str.__setattr__(self, key, value)

	def getStr(self):
		return self._str

	def appendStr(self, aStr):
		self._str += aStr + '\n'


class favoritesParser():
	'''解析多种浏览器导出的搜藏夹文件

	'''

	def __init__(self, filePath):
		self._filePath = os.path.abspath(os.curdir + r'\fDoc.html')

	# copyfile(filePath, self._filePath)

	# 解析列表
	def _pList(self, aList):
		if not isinstance(aList, list):
			return None

		s = ""

		for item in aList:
			if isinstance(item, list):
				s = self._pList(item)
			elif isinstance(item, dict):
				s = s + self._pDict(item)

		return s

	# 解析词典
	def _pDict(self, aDict):
		'''遍历解析某个词典中的键值对,返回键值对组成的文本.

		:param aDict: 要解析的词典对象
		:type aDict: list
		:return: 组合完成的多行文本
		:rtype: str
		'''

		# print(repr(aItem))
		# print(type(aItem))
		# return None

		s, name, url = '', '', ''

		for item in aDict:
			if isinstance(item, list):
				re = re + self._pList(item)
			elif isinstance(item, dict):
				for o in item:
					# 如果没有url的就是dir
					if dict(o).has_key('children'):
						s = s + self._pList(item)
					else:
						url = o['url']

					if dict(o).has_key('name'):
						name = o['name']
					else:
						return ''

		re = ''.join('name:%s\nurl:%s\n' % (name, url))
		print(re)
		return re

	def dumpAll(self):
		'''奇虎360极速浏览器导出的搜藏夹文件解析.

		:param filePath: 一个html文件的完整路径.
		:type filePath: str
		:return: [{'title':'url title', 'url':'http link'}, ...]
		:rtype: list
		'''

		# 不能直接用file.open打开
		# f = open(self._filePath)
		# 而必须这样读文件
		f = codecs.open(self._filePath, 'r', 'utf-8')

		# 已知文件的编码是 utf-8
		# encoding = detect(f.read(1000))['encoding']
		# print(encoding)
		# exit(0)

		# f = file(self._filePath, 'r')
		fout = codecs.open('_out.txt', 'wb', 'gbk')
		# fout = open('_out.txt', 'w')

		try:
			# 获取文件内的所有内容
			fc = f.read()

			# 如果要正确打印中文,必须这样
			# sj = json.dumps(fc, ensure_ascii=False)

			s = json.loads(fc)
			# print(s)
			# exit(0)
			items = s['roots']['bookmark_bar']['children']

			myObjList = []
			for item in items:
				# print(repr(item).decode('utf-8'))
				# 全部是 dict
				# print(type(item['children']))
				# print(len(item['children']))
				# print(item['children'])
				try:
					o = item['children']
					for i in o:
						# print(type(i))
						obj = {}
						try:
							# print(i['type'])
							obj['name'] = i['name']
							obj['url'] = i['url']
							# print(obj)
							myObjList.append(obj)
							fout.write('name: %s\nurl: %s\n' % (i['name'], i['url']))
						except:
							if obj.has_key('children'):
								print('%s还有子目录' % (i['name']))

				except:
					pass


				# if raw_input() == 'e':
				# 	exit(0)
				# continue
				# myObjList.sort('url')
				# print(myObjList)

				# self.WriteFile(fout, json.dumps(myObjList, ensure_ascii=False))

		finally:
			f.close()
			fout.close()

		return None

	def WriteFile(filePath, u, encoding="gbk"):
		with codecs.open(filePath, "wb") as f:
			f.write(u.encode(encoding, errors="ignore"))


def main():
	fpPath = r'c:\Users中国字\Fonny\AppData\Local\360Chrome\Chrome\User Data\Default\360UID26203830_V8\Bookmarks.bak'
	fp = favoritesParser(fpPath)

	o = fp.dumpAll()
	print(o)


if __name__ == '__main__':
	main()
